package cn.jinzhu.netty.c1;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Scanner;
@Slf4j
public class HelloClient {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        //启动类
        ChannelFuture connect = new Bootstrap()
                //添加eventloop 表示一个线程一个selector
                .group(new NioEventLoopGroup())
                //添加客户端channel
                .channel(NioSocketChannel.class)
                //添加处理器
                .handler(
                        //添加handler 初始化添加的handler
                        new ChannelInitializer<NioSocketChannel>() {
                            @Override
                            //进行初始化添加的handler  建立连接会被调用
                            protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                                //客户端要添加服务端发送过来的数据要进行转码字符串转bytebuff  服务端也是一样StringEncoder
                                nioSocketChannel.pipeline().addLast(new StringEncoder());
                                //netty专属日志打印
                                nioSocketChannel.pipeline().addLast(new LoggingHandler());
                            }
                        })
                //建立连接
                .connect(new InetSocketAddress("127.0.0.1", 8080));
          /*      //建立连接后才会执行 阻塞方法  也就是sync调用连接对象socketchannel然后调用write发送数据给服务端
                .sync()
                //代表连接对象
                .channel()
                //向服务端发送数据
                .writeAndFlush("hello,world");*/


        //同步阻塞
        Channel channel = connect.sync().channel();

        new Thread(() ->{
            Scanner scanner = new Scanner(System.in);
            while (true) {
                String line = scanner.nextLine();
                if ("q".equals(line)) {
                    channel.close(); // close 异步操作 1s 之后
//                    log.debug("处理关闭之后的操作"); // 不能在这里善后
                    break;
                }
                channel.writeAndFlush(line);
            }
        },"nihao").start();
        // 获取 CloseFuture 对象， 1) 同步处理关闭， 2) 异步处理关闭
        ChannelFuture channelFuture = channel.closeFuture();
        channelFuture.addListener((ChannelFutureListener) future -> {
            log.debug("处理关闭之后的操作");
            group.shutdownGracefully();
        });

    }
}